#include "CF_Core.h"

CCF_CfgReader::CCF_CfgReader(char *szFileName) 
{
  this->m_file = fopen(szFileName, "rb");
}

CCF_CfgReader::~CCF_CfgReader() 
{
  if (m_file != NULL)
  {
    fclose (m_file);
  }
}

bool CCF_CfgReader::IsReady()
{
  return m_file != NULL;
}
bool CCF_CfgReader::ReadEntry (char **ppNameOut, char **ppValueOut) 
{
  if ((m_file != NULL)&&(feof (m_file)))
  {
    char c = 0;

    while (fread (&c, 1, 1, m_file) != 0) 
    {
      if ((c != ' ') && (c != '\t') && (c != '\n') && (c != '\r')) 
      {
        if (c == '[') 
        {	
          while ((fread (&c, 1, 1, m_file) != 0)&&(c != ']')){}

          if (feof (m_file))
            return false;

        } 
        else 
        {	
          fseek (m_file, -1, SEEK_CUR);
          break;
        }
      }
    }

    if (feof (m_file))
      return false;

    char buf [1000];
    int nChars = 0;

    while (fread (&buf [nChars], 1, 1, m_file) != 0)
    {
      if( buf[nChars] != '=' ) 
      {	
        if ((buf[nChars] != ' ') && (buf[nChars] != '\t'))
        {
          nChars++;
        }
      }
      else 
      {
        buf[nChars] = 0;
        break;
      }
    }

    if (feof (m_file))
      return false;

    *ppNameOut = new char [nChars + 1];
    memcpy( *ppNameOut, buf, nChars + 1 );


    while ((fread (&c, 1, 1, m_file) != 0)&&(c != '\"')){}

    if (feof (m_file))
      return false;

    nChars = 0;

    while (fread (&buf [nChars], 1, 1, m_file) != 0)
    {
      if (buf[nChars] != '\"') 
      {
        nChars++;
      }
      else 
      {
        buf[nChars] = 0;
        break;
      }
    }

    if (feof (m_file))
      return false;

    *ppValueOut = new char [nChars + 1];
    memcpy( *ppValueOut, buf, nChars + 1 );
  }

  return false;
}
